#include "connection/ZmqConnection.h"
#include <mutex>

namespace zeroplus::mq
{

    void ZmqConnection::Bind()
    {
        socket_->bind(uri_.c_str());
    }

    void ZmqConnection::UnBind()
    {
        socket_->unbind(uri_.c_str());
    }

    void ZmqConnection::Connect()
    {
        socket_->connect(uri_.c_str());
    }

    void ZmqConnection::DisConnect()
    {
        socket_->disconnect(uri_.c_str());
    }

    ssize_t ZmqConnection::WriteMsg(zmqpp::message_t &message, int sendFlag)
    {
        size_t bytesWritten = Size(message);
        // LOG_DEBUG("bytesWritten=%d", bytesWritten);
        socket_->send(message, sendFlag);
        if (bytesWritten)
        {
            totalBytesWritten_ += bytesWritten;
            totalMsgWritten_ += 1;
            // LOG_INFO("Successfully send message, size=%d", bytesWritten);
            return bytesWritten;
        }
        else
        {
            LOG_ERROR("Failed to send message");
            return -1;
        }
    }

    std::tuple<zmqpp::message_t, bool> ZmqConnection::ReadMsg()
    {
        zmqpp::message_t message;
        bool res = socket_->receive(message, zmqpp::socket::normal);
        size_t bytesRead = Size(message);
        if (res)
        {
            totalBytesRead_ += bytesRead;
            totalMsgRead_ += 1;
            // LOG_INFO("Received: size %d", bytesRead);
            return std::make_tuple(std::move(message), true);
        }
        else
        {
            message << "";
            LOG_ERROR("Failed to recv message");
            return std::make_tuple(std::move(message), false);
        }
    }

}
